<?php
/**
 * MySQL - 执行上传的SQL文件
 */

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    // 检查是否有文件上传
    if (!isset($_FILES['sql_file']) || $_FILES['sql_file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('文件上传失败');
    }
    
    $file = $_FILES['sql_file'];
    
    // 验证文件类型
    if (!str_ends_with(strtolower($file['name']), '.sql')) {
        throw new Exception('只允许上传.sql文件');
    }
    
    // 读取SQL文件内容
    $sqlContent = file_get_contents($file['tmp_name']);
    if ($sqlContent === false) {
        throw new Exception('无法读取SQL文件内容');
    }
    
    // 读取数据库配置
    $config = require '../../config.php';
    $mysqlConfig = $config['databases']['mysql'] ?? [];
    
    // 检查MySQL是否启用
    if (empty($mysqlConfig['enabled'])) {
        throw new Exception('MySQL服务未启用，请先在配置中启用');
    }
    
    // 验证必要的配置项
    if (empty($mysqlConfig['host']) || empty($mysqlConfig['database']) || 
        empty($mysqlConfig['username']) || empty($mysqlConfig['password'])) {
        throw new Exception('MySQL配置不完整，请先保存完整的数据库配置');
    }
    
    // 连接数据库
    $host = $mysqlConfig['host'];
    $port = $mysqlConfig['port'] ?? '3306';
    $database = $mysqlConfig['database'];
    $username = $mysqlConfig['username'];
    $password = $mysqlConfig['password'];
    
    // 创建PDO连接
    $dsn = "mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4";
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
    ]);
    
    // 开启事务
    $pdo->beginTransaction();
    
    try {
        // 分割SQL语句（按分号分隔，但要处理字符串中的分号）
        $statements = [];
        $currentStatement = '';
        $inString = false;
        $stringChar = '';
        
        for ($i = 0; $i < strlen($sqlContent); $i++) {
            $char = $sqlContent[$i];
            
            // 处理字符串
            if (($char === "'" || $char === '"') && ($i === 0 || $sqlContent[$i-1] !== '\\')) {
                if (!$inString) {
                    $inString = true;
                    $stringChar = $char;
                } elseif ($char === $stringChar) {
                    $inString = false;
                }
            }
            
            // 如果遇到分号且不在字符串中
            if ($char === ';' && !$inString) {
                $currentStatement .= $char;
                $stmt = trim($currentStatement);
                if (!empty($stmt) && !str_starts_with($stmt, '--') && !str_starts_with($stmt, '#')) {
                    $statements[] = $stmt;
                }
                $currentStatement = '';
            } else {
                $currentStatement .= $char;
            }
        }
        
        // 添加最后一条语句
        $stmt = trim($currentStatement);
        if (!empty($stmt) && !str_starts_with($stmt, '--') && !str_starts_with($stmt, '#')) {
            $statements[] = $stmt;
        }
        
        // 执行所有SQL语句
        $executedCount = 0;
        $errors = [];
        
        foreach ($statements as $index => $statement) {
            try {
                $pdo->exec($statement);
                $executedCount++;
            } catch (PDOException $e) {
                $errors[] = "语句 " . ($index + 1) . " 执行失败: " . $e->getMessage();
                // 继续执行其他语句，不中断
            }
        }
        
        // 如果有错误，回滚事务
        if (!empty($errors)) {
            $pdo->rollBack();
            throw new Exception("部分SQL语句执行失败:\n" . implode("\n", $errors));
        }
        
        // 提交事务
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "成功执行 {$executedCount} 条SQL语句"
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
